// 授人以鱼不如授人以渔
const { src, dest, series } = require('gulp');
const webserver = require('gulp-webserver');
const url = require('url')
const bodyParser = require('body-parser')
const autopre = require('gulp-autoprefixer')
const csso = require('gulp-csso')
const gulpsass = require('gulp-sass')
const concat = require('gulp-concat');
const del = require('del');
// gulp.src gulp.dest gulp.series gulp.watch

// http.createServer((req, res) => {})

function sass() {
  return src('src/css/*.scss')
    .pipe(gulpsass())
    .pipe(autopre({ cascade: false }))
    .pipe(concat('app.css'))
    .pipe(dest('dist/css'))
}


function server() {
  return src('src')
    .pipe(webserver({
      port: 9999,
      // open: true,
      livereload: true,
      middleware: [
        bodyParser.urlencoded({
          extended: false
        }),
        bodyParser.json(),
        (req, res, next) => {
          // 拦截请求request->req  返回响应 response->res

          const address = url.parse(req.url, true).pathname;
          const method = req.method;
          req.query = url.parse(req.url, true).query;

          if (method === 'GET' && address === '/api/login') {
            // res.setHeader('Content-Type', 'application/json')
            // console.log('请求完整地址:', req.url)
            // console.log('请求完整地址的对象形式:', url.parse(req.url, true))
            // console.log('请求地址:', url.parse(req.url, true).pathname)
            // console.log('请求方式:', req.method)

            res.end(`get参数：${JSON.stringify(req.query)}, post参数： ${JSON.stringify(req.body)}`)
            return;
          }

          next()
        }]
    }))
}

// npx gulp 
// gulp -g 
// gulp server

// 本地安装 npx 直接调用本地包
// npx gulp 本地node_moudules中的gulp

// module.exports = {
//   server
// }

function delFile(cb) {
  return del([
    'dist/css/*.css',
    // 这里我们使用一个通配模式来匹配 `mobile` 文件夹中的所有东西
    'dist/mobile/**/*',
  ], cb);
}

exports.default = series(delFile, sass, server) 